<template>
  <div class="i-query">
    <div class="query-table">
      <div class="table-title">
        <span>属性表</span>
        <i class="el-icon-circle-close close-btn" @click="close"></i>
      </div>

      <div class="table-box" v-if="showTab">
        <el-tabs v-model="activeName" @tab-click="switchTab">
          <el-tab-pane v-for="(item, index) in tabData" :key="index" :label="item.name" :name="item.name">
            <div class="table-search">
              <span>查询字段</span>

              <el-select v-model="item.queryParams.field" placeholder="请选择字段" popper-class="query-field">
                <el-option v-for="(option, key) in item.fieldList" :key="key" :label="option.name" :value="option.name">
                </el-option>
              </el-select>

              <div clear="query-value">
                <el-input v-model="item.queryParams.value" placeholder="输入以查询"></el-input>
              </div>

              <el-button type="info" @click="queryLayer(item)">查询</el-button>
              <el-button type="info" plain @click="resetTabel(item)">清空</el-button>
            </div>

            <div class="table-body">
              <el-table :data="item.queryData" border style="width: 100%" :row-style="{height:'32px', 'box-sizing': 'border-box'}" :cell-style="{padding: '0px'}">
                <el-table-column v-for="(option, key)  in item.fieldList" :key="key" :prop="option.name" :label="option.name"></el-table-column>
              </el-table>
            </div>

            <div class="table-statistics">
              <span>共{{item.queryData.length}}条数据</span>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 属性弹窗 -->
    <div class="popup-box attribute-query" ref="popupEle" v-if="showPopup">
      <div class="popup-content">
        <div class="content-close" @click="removePopup">×</div>

        <div class="content-left">
          <div class="content-title">
            <span>要素&注记</span>
          </div>

          <div class="left-list">
            <div class="list-item">
              <div class="item-box" v-for="(item, index) in cardData" :class="{'is-select': item.isCheck}" @click="switchCardName(item)">
                <span class="beyond-txt" :title="item.name">{{item.name}}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="content-right">
          <div class="content-title">
            <span>属性信息</span>
          </div>

          <div class="right-body">
            <div class="body-item" v-for="(item, index) in cardItemData" :key="index">
              <div class="item-title">
                <span class="beyond-txt" :title="item.id">{{item.id || ''}}</span>
              </div>

              <div class="item-box" v-for="(option, key) in item" :key="key">
                <div class="item-left"><span class="beyond-txt" :title="key">{{key}}</span></div>
                <div class="item-right"><span class="beyond-txt" :title="option">{{option}}</span></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ['selectLayerNode'],

  data() {
    return {
      nodeAttribute: null,
      showTab: false,
      activeName: '',
      tabData: [],
      serverInfo: {},
      fieldList: [],
      queryTable: [],
      allQueryTable: [],
      showPopup: false,
      cardData: [],
      cardItemData: []
    };
  },

  methods: {
    // 获取图层列表
    async getLengend() {
      this.getServerInfo();
      const { serverIpPort } = this.nodeAttribute;
      const { serverName, layerName } = this.serverInfo;
      if (!serverName || !layerName) return;

      try {
        const res = await this.$get(`${serverIpPort}/mapserver/styleInfo/${serverName}/${layerName}/layer.json`);
        if (res && res.length) {
          let tabData = [];
          res.forEach((item, index) => {
            this.getfieldList(item.name).then(fieldList => {
              if (fieldList.length) {
                this.getAttributeTable(item.name, fieldList).then(queryData => {
                  const tabItem = {
                    name: item.name,
                    fieldList,
                    queryParams: {
                      field: '',
                      value: ''
                    },
                    queryData: queryData,
                    allQueryData: queryData
                  };
                  tabData.push(tabItem);

                  if (tabData.length == res.length) {
                    this.clickMap();
                    this.$nextTick(() => {
                      this.tabData = tabData;
                      this.activeName = tabData[0].name;
                      this.showTab = true;
                      console.log(this.tabData);
                    });
                  }
                });
              }
            });
          });
        }
      } catch (error) {
        console.log('获取字段列表报错：', error);
      }
    },

    // 获取图层字段
    async getfieldList(name) {
      const { serverIpPort } = this.nodeAttribute;
      const { serverName } = this.serverInfo;
      if (!serverName || !name) return;
      let fieldList = [];
      try {
        const res = await this.$get(`${serverIpPort}/mapserver/${serverName}/${name}/getinfo.json`);
        if (res && res.fields && res.fields.length) {
          fieldList = res.fields.filter(e => e.name != 'geom');
        }
      } catch (error) {
        console.log('获取字段列表报错：', error);
      }
      return fieldList;
    },

    // 查询图层属性表
    async getAttributeTable(name, fieldList) {
      const { serverIpPort } = this.nodeAttribute;
      const { serverName } = this.serverInfo;
      if (!serverName || !name || !fieldList.length) return;
      let queryData = [];
      try {
        const res = await this.$get(`${serverIpPort}/mapserver/${serverName}/${name}/14/query`);
        if (res && res.length) {
          res.forEach(item => {
            let fildObj = {};
            fieldList.forEach(field => {
              fildObj[field.name] = item[field.name];
            });
            queryData.push(fildObj);
          });
        }
      } catch (error) {
        console.log('获取属性表报错', error);
      }
      return queryData;
    },

    getServerInfo() {
      const { serverType, serverUrl } = this.nodeAttribute;
      let serverName = '';
      let layerName = '';
      switch (serverType) {
        case 'WMTS':
          const wmtsServerNameReg = new RegExp("(?<=/1.0/).*?(?=/)");
          serverName = serverUrl.match(wmtsServerNameReg) != null ? serverUrl.match(wmtsServerNameReg)[0] : '';
          const wmtsLayerNameReg = new RegExp(`(?<=/${serverName}/).*?(?=/)`);
          layerName = serverUrl.match(wmtsLayerNameReg) != null ? serverUrl.match(wmtsLayerNameReg)[0] : '';
          break;

        case 'WMS':
          const wmsServerNameReg = new RegExp("(?<=/1.1.1/).*?(?=/)");
          serverName = serverUrl.match(wmsServerNameReg) != null ? serverUrl.match(wmsServerNameReg)[0] : '';
          const wmsLayerNameReg = new RegExp(`(?<=/${serverName}/).*?(?=/)`);
          layerName = serverUrl.match(wmsLayerNameReg) != null ? serverUrl.match(wmsLayerNameReg)[0] : '';
          break;

        case 'XYZ':
          const typeReg = new RegExp("(?<=/mapserver/).*?(?=/)");
          const type = serverUrl.match(typeReg) != null ? serverUrl.match(typeReg)[0] : '';
          const mapServerNameReg = new RegExp(`(?<=/${type}/).*(?=/)`);
          const mapLayerNameReg = new RegExp("(?<=styleId=)[^&]*");
          serverName = serverUrl.match(mapServerNameReg) != null ? serverUrl.match(mapServerNameReg)[0] : '';
          layerName = serverUrl.match(mapLayerNameReg) != null ? serverUrl.match(mapLayerNameReg)[0] : '';
          break;

        default:
          break;
      }
      this.serverInfo = { serverName, layerName };
    },

    // 切换tab
    switchTab() {

    },

    // 查询列表
    queryLayer(option) {
      const { queryParams } = option;
      const { field } = queryParams;
      const value = queryParams.value.replace(/\s*/g, "");
      if (!value) return;
      let queryData = [];
      option.allQueryData.forEach(item => {
        if (item[field] == value) {
          queryData.push(item);
        }
      });
      option.queryData = queryData;
    },

    resetTabel(option) {
      option.queryParams = {
        field: '',
        value: ''
      };
      option.queryData = option.allQueryData;
    },

    clickMap() {
      this.removePopup();
      !this.handler && (this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas));
      this.handler.setInputAction((e) => {
        let cartesian = null;
        let primitive = this.viewer.scene.pick(e.position);
        if (primitive) {
          cartesian = this.viewer.scene.pickPosition(e.position);
        } else {
          let ray = this.viewer.camera.getPickRay(e.position);
          cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
        }
        if (!cartesian) return;
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        const lng = Cesium.Math.toDegrees(cartographic.longitude);
        const lat = Cesium.Math.toDegrees(cartographic.latitude);
        const height = cartographic.height;
        const option = { lng, lat, height, cartesian };
        if (this.tabData.length) {
          let cardData = [];
          this.tabData.forEach(async (item, index) => {
            const cardItem = await this.getQueryPointData({ ...option, name: item.name });
            cardData.push({
              name: item.name,
              cardItem,
              isCheck: false
            });

            if (index == this.tabData.length - 1) {
              cardData[0].isCheck = true;
              this.cardData = cardData;
              this.cardItemData = cardData[0].cardItem;
              this.showPopup = true;
              this.$nextTick(() => {
                let params = {
                  element: this.$refs.popupEle,
                  position: option.cartesian,
                  offset: { x: 0, y: 0 },
                };
                const cardPopup = new Custom.Overlay(params);
                this.viewer.addOverlay(cardPopup);
                this.cardPopup = cardPopup;
              });
            }
          });
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },

    switchCardName(option) {
      this.cardData.forEach(item => {
        item.isCheck = item.name == option.name ? true : false;
      });
      this.cardItemData = this.cardData.find(e => e.name == option.name).cardItem;
    },

    clearClick() {
      this.handler && this.handler.destroy();
      this.handler = null;
      this.removePopup();
    },

    removePopup() {
      this.cardPopup && this.cardPopup.destroy();
      this.cardPopup = null;
      this.showPopup = false;
    },

    async getQueryPointData(option) {
      const { serverIpPort } = this.nodeAttribute;
      const { serverName } = this.serverInfo;
      if (!serverName) return;
      let cardItem = [];
      try {
        const res = await this.$get(`${serverIpPort}/mapserver/${serverName}/${option.name}/query?spatialFilter=POINT(${option.lng} ${option.lat})&withGeometry=true`);
        if (res && res.length) {
          cardItem = res;
        }
      } catch (error) {
        console.log('查询图层点报错：', error);
      }
      return cardItem;
    },

    close() {
      this.$emit('close');
    }
  },

  created() {
    this.nodeAttribute = this.selectLayerNode.attribute;
    this.viewer = this.Global.viewer;
    this.handler = null;
    this.cardPopup = null;
    this.getLengend();
  },

  beforeDestroy() {
    this.clearClick();
  }
}
</script>

<style lang="less" scoped>
.i-query {
  /deep/.el-tabs {
    padding: 0 10px;
    box-sizing: border-box;
    .el-tabs__item {
      font-size: 13px;
      color: #fff;
    }
  }

  .query-table {
    position: fixed;
    bottom: 40px;
    left: 50%;
    transform: translateX(-35%);
    width: 800px;
    background-color: #333333;
    z-index: 11;
    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      box-sizing: border-box;
      font-size: 14px;
      font-weight: 600;
      color: #fff;
      .close-btn {
        cursor: pointer;
      }
    }

    /deep/.table-search {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
      box-sizing: border-box;
      font-size: 13px;
      color: #fff;
      .el-input__inner {
        width: 380px;
        height: 30px;
        background: rgba(0, 0, 0, 0);
        font-size: 13px;
        color: #fff;
      }

      .el-select {
        width: 200px;
        height: 30px;
        .el-input__inner {
          width: 100%;
          background-color: rgba(0, 0, 0, 0);
        }
      }

      .el-button {
        padding: 6px 12px;
      }
    }

    /deep/.table-body {
      height: 160px;
      overflow-y: auto;
      padding: 10px;
      margin: 10px;
      box-sizing: border-box;
      .el-table,
      .el-table__row {
        background: #3f3f3f;
        th.el-table__cell {
          background: #3f3f3f;
        }
      }

      .el-table {
        .el-table__header {
          .has-gutter {
            .el-table__cell {
              height: 32px;
              padding: 0;
            }
          }
        }
      }
    }

    .table-statistics {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 0 10px 10px 10px;
      box-sizing: border-box;
      font-size: 14px;
      color: #fff;
    }
  }
}

.beyond-txt {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
</style>

<style lang="less">
.query-field {
  background-color: #444444;
  .el-select-dropdown__list {
    li {
      font-size: 14px;
      color: #fff;
    }

    .hover {
      background-color: #333;
    }
  }
}

.popup-box {
  position: absolute !important;
  .popup-content {
    position: absolute;
    left: -270px;
    top: -338px;
    display: flex;
    align-items: center;
    width: 540px;
    height: 328px;
    padding: 13px 19px;
    box-sizing: border-box;
    background-color: #fff;
    box-shadow: 0 3px 14px rgba(0, 0, 0, 0.4);
    border-radius: 5px;
    &::after {
      content: ' ';
      position: absolute;
      bottom: -25px;
      left: 50%;
      transform: translateX(-50%);
      height: 0;
      width: 0;
      border: 15px solid transparent;
      border-top: 10px solid #fff;
    }

    .content-close {
      position: absolute;
      top: 0;
      right: 0;
      padding: 4px 4px 0 0;
      border: none;
      text-align: center;
      width: 18px;
      height: 14px;
      font: 16px/14px Tahoma, Verdana, sans-serif;
      color: #c3c3c3;
      text-decoration: none;
      font-weight: bold;
      background: transparent;
      cursor: pointer;
    }

    .content-title {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 30px;
      font-size: 14px;
      font-weight: 600;
    }

    .content-left {
      width: 150px;
      height: 100%;
      padding-right: 10px;
      box-sizing: border-box;
      border-right: 1px solid #eee;
      .left-list {
        height: calc(100% - 30px);
        overflow-y: auto;
        .item-box {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 30px;
          padding: 0 10px;
          box-sizing: border-box;
          background-color: #edf3fe;
          margin-bottom: 10px;
          font-size: 13px;
          color: #333;
          cursor: pointer;
        }

        .is-select {
          background-color: #ffe48d;
        }
      }
    }

    .content-right {
      width: calc(100% - 150px);
      height: 100%;
      padding-left: 10px;
      box-sizing: border-box;
      .right-body {
        height: calc(100% - 30px);
        overflow-y: auto;
        .body-item {
          .item-title {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
            height: 30px;
            padding: 0 10px;
            box-sizing: border-box;
            background-color: #edf3fe;
            margin-bottom: 10px;
            font-size: 14px;
            color: #333;
          }
          .item-box {
            display: flex;
            justify-content: space-between;
            height: 30px;
            .item-left,
            .item-right {
              display: flex;
              align-items: center;
              overflow: hidden;
              font-size: 14px;
              color: #333;
            }

            .item-left {
              justify-content: flex-end;
              width: 128px;
              height: 100%;
              padding: 0 10px;
              box-sizing: border-box;
              border: 1px solid #eee;
            }

            .item-right {
              width: calc(100% - 128px);
              height: 100%;
              padding: 0 10px;
              box-sizing: border-box;
              border: 1px solid #eee;
              border-left: none;
            }
          }
        }
      }
    }
  }
}
</style>